from genutils.simple_ga import Population
from bEandI_classes_python_only import *

class ThisPop(Population):
    def score_model(self,gene,printme=False):
        values = []
        for allyl in gene.allyls:
            values.append(allyl.value)
        self.c.set_synapses_from_list(values)
        self.c.exercise()
        residuals = self.c.calculate_residuals()
        return sum(residuals)

thispop = ThisPop(30,"Imc_ga.parameters")
thispop.c = Cell(config_filename='config_Ionly')
thispop.c.set_synapses('Imc_only.par')
thispop.mutate_rate = 0.05
thispop.cross_rate = 0.2

for i in range(40):
    thispop.evolve()
    avg_score = 0
    for gene in thispop.genes:
        avg_score += gene.score
    avg_score /= thispop.num_genes
    print "Average score = " + str(avg_score)

    printme = False
    for gene in thispop.generation[-1]:
        if gene.score == 0:
            printme = True
    if printme:
        print thispop
        break

# show the results of all this hard work.
# ... plot the best result of the final generation
values = []
for allyl in thispop.generation[-1][0].allyls:
    values.append(allyl.value)

thispop.c.set_synapse_from_list(values)
thispop.c.exercise()
thispop.c.pylab_plot()
import pylab
pylab.show()

    

